package cn.edu.lcvc.ebuy_23rj2.web.action.backstage;

import cn.edu.lcvc.ebuy_23rj2.model.Admin;
import cn.edu.lcvc.ebuy_23rj2.model.common.ResponseData;
import cn.edu.lcvc.ebuy_23rj2.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value ="/api/backstage" )
public class LoginLogoutController {
    @Autowired
    private AdminService adminService;
    @PostMapping("/login")
    public ResponseData login(String username, String password, HttpSession session){
        ResponseData responseData=null;
        if(adminService.login(username,password)){//如果密码正确
            //将登录后的用户信息保存到服务器中。
            //session对象的存储有效期：如果浏览器关闭则session对象被清空；session的默认有效期是20分钟，如果20分钟内不执行本站的任何操作则本站session自动销毁

            session.setAttribute("admin",adminService.getAdminByUsername(username));
            //如果登录成功，则跳转到后台管理系统首页(main.html)
            responseData=ResponseData.success();
        }else {//如果密码错误
            //如果登录失败，则跳转到后台管理系统登录页面(login.html)
            responseData=ResponseData.error("密码错误");
        }
        return responseData;
    }

    @GetMapping("/logout")
    public ResponseData logout(HttpSession session){
        session.removeAttribute("admin");
        return ResponseData.success();
    }

    //获取当前登陆信息
    @GetMapping("/session")
    public ResponseData session(HttpSession session){
        return ResponseData.success((Admin)session.getAttribute("admin"));
    }
}
